import 'package:flutter/material.dart';
import 'dart:convert';
import '../models/important_day.dart';
import '../repositories/important_days_repository.dart';

class ImportantDaysProvider extends ChangeNotifier {
  final ImportantDaysRepository _repository;
  List<ImportantDay> _importantDays = [];
  List<ImportantDay> _futureDays = [];
  List<ImportantDay> _pastDays = [];
  List<ImportantDay> _upcomingDays = [];
  bool _isLoading = false;
  String? _error;

  List<ImportantDay> get importantDays => _importantDays;
  List<ImportantDay> get futureDays => _futureDays;
  List<ImportantDay> get pastDays => _pastDays;
  List<ImportantDay> get upcomingDays => _upcomingDays;
  bool get isLoading => _isLoading;
  String? get error => _error;

  ImportantDaysProvider(this._repository) {
    _loadImportantDays();
  }

  Future<void> _loadImportantDays() async {
    _setLoading(true);
    
    try {
      final response = await _repository.getAllImportantDays();
      if (response.isSuccess && response.data != null) {
        _importantDays = response.data!;
        await _updateDerivedLists();
        _clearError();
      } else {
        _setError(response.error ?? '加载重要日子数据失败');
      }
    } catch (e) {
      _setError('加载重要日子数据失败: $e');
    } finally {
      _setLoading(false);
    }
  }
  
  Future<void> _updateDerivedLists() async {
    try {
      final futureResponse = await _repository.getFutureDays();
      if (futureResponse.isSuccess) {
        _futureDays = futureResponse.data ?? [];
      }
      
      final pastResponse = await _repository.getPastDays();
      if (pastResponse.isSuccess) {
        _pastDays = pastResponse.data ?? [];
      }
      
      final upcomingResponse = await _repository.getUpcomingDays();
      if (upcomingResponse.isSuccess) {
        _upcomingDays = upcomingResponse.data ?? [];
      }
    } catch (e) {
      // 错误处理，但不阻断主流程
    }
  }

  void _addSampleData() {
    // 这个方法不再需要，示例数据在 Repository 层处理
  }

  Future<void> _saveImportantDays() async {
    // 这个方法不再需要，在 Repository 层处理
  }

  Future<String> getNextDayReminder() async {
    try {
      if (_futureDays.isEmpty) {
        return '暂无即将到来的重要日子';
      }
      
      final nextDay = _futureDays.first;
      final daysUntil = nextDay.date.difference(DateTime.now()).inDays;
      
      if (daysUntil == 0) {
        return '今天是 ${nextDay.title}！';
      } else if (daysUntil == 1) {
        return '明天是 ${nextDay.title}';
      } else {
        return '还有 $daysUntil 天就是 ${nextDay.title}';
      }
    } catch (e) {
      return '暂无即将到来的重要日子';
    }
  }

  Future<void> addImportantDay(ImportantDay day) async {
    _setLoading(true);
    
    try {
      final response = await _repository.createImportantDay(day);
      if (response.isSuccess && response.data != null) {
        _importantDays.add(response.data!);
        await _updateDerivedLists();
        _clearError();
      } else {
        _setError(response.error ?? '添加重要日子失败');
      }
    } catch (e) {
      _setError('添加重要日子失败: $e');
    } finally {
      _setLoading(false);
    }
  }

  Future<void> updateImportantDay(ImportantDay updatedDay) async {
    _setLoading(true);
    
    try {
      final response = await _repository.updateImportantDay(updatedDay);
      if (response.isSuccess && response.data != null) {
        final index = _importantDays.indexWhere((day) => day.id == updatedDay.id);
        if (index != -1) {
          _importantDays[index] = response.data!;
          await _updateDerivedLists();
          _clearError();
        }
      } else {
        _setError(response.error ?? '更新重要日子失败');
      }
    } catch (e) {
      _setError('更新重要日子失败: $e');
    } finally {
      _setLoading(false);
    }
  }

  Future<void> deleteImportantDay(String id) async {
    _setLoading(true);
    
    try {
      final response = await _repository.deleteImportantDay(id);
      if (response.isSuccess) {
        _importantDays.removeWhere((day) => day.id == id);
        await _updateDerivedLists();
        _clearError();
      } else {
        _setError(response.error ?? '删除重要日子失败');
      }
    } catch (e) {
      _setError('删除重要日子失败: $e');
    } finally {
      _setLoading(false);
    }
  }

  bool _isSameDay(DateTime date1, DateTime date2) {
    return date1.year == date2.year &&
        date1.month == date2.month &&
        date1.day == date2.day;
  }
  
  void _setLoading(bool loading) {
    _isLoading = loading;
    notifyListeners();
  }
  
  void _setError(String error) {
    _error = error;
    notifyListeners();
  }
  
  void _clearError() {
    _error = null;
    notifyListeners();
  }
}